package com.woniuxy.mapper.impl;

import com.woniuxy.mapper.StuDao;
import com.woniuxy.entity.Stu;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 作者
 * @create 2025-08-11 17:04
 */
public class StuDaoImpl implements StuDao {
    @Override
    public void insert(Stu stu) throws SQLException, ClassNotFoundException {
        Connection connection = JdbcUtil.getConnection();
        String sql="insert into stu values(?,?,?,?)";
        Object[] obj={stu.getSid(),stu.getSname(),stu.getPassword(),stu.getAge()};
        JdbcUtil.executeUpdate(connection, sql, obj);
    }

    @Override
    public void update(Stu stu) throws SQLException, ClassNotFoundException {
        Connection connection = JdbcUtil.getConnection();
        String sql="update stu set sname=?,password=?,age=? where sid=?";
        Object[] obj={stu.getSname(),stu.getPassword(),stu.getAge(),stu.getSid(),};
        JdbcUtil.executeUpdate(connection, sql, obj);
    }

    @Override
    public void deleteBySid(int sid) throws SQLException, ClassNotFoundException {
        Connection connection = JdbcUtil.getConnection();
        String sql="delete from stu where sid=?";
        JdbcUtil.executeUpdate(connection, sql, sid);
    }

    @Override
    public Stu selectBySid(int sid) throws SQLException, ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        Connection connection = JdbcUtil.getConnection();
        String sql="select * from stu where sid=?";
        return  JdbcUtil.executeQueryOne(connection, Stu.class, sql, sid);
    }

    @Override
    public List<Stu> selectAll() throws SQLException, ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        Connection connection = JdbcUtil.getConnection();
        String sql="select * from stu ";
        return  JdbcUtil.executeQueryList(connection, Stu.class, sql);
    }

    @Override
    public List<Stu> selectBySname(String sname) throws SQLException, NoSuchFieldException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        Connection connection = JdbcUtil.getConnection();
        //  oK
//        String sql="select * from stu where sname like CONCAT('%',?,'%')";
        //   ok
        String sql="select * from stu where sname like  '%' ? '%'";
        //error
//        String sql="select * from stu where sname like '%?%' ";

        System.out.println(sql);
        return  JdbcUtil.executeQueryList(connection, Stu.class, sql,sname);
    }
}
